package com.example.cameraview;

import java.util.Map;

import android.content.Context;

import com.smaxe.uv.client.ICamera;
import com.smaxe.uv.client.INetConnection;
import com.smaxe.uv.client.INetStream;
import com.smaxe.uv.client.License;
import com.smaxe.uv.client.NetConnection;
import com.smaxe.uv.client.NetStream;

public class RTMPConnectionUtil {
	private static final String red5_url = "rtmp://192.168.1.202:1935/videoSurveillance";

	private NetConnection connection;
	private NetStream netStream;

	private Context context;

	public void ConnectRed5(Context context) {

		License.setKey("A1060-23DB7-D400A-12491-F15E7");
		connection = new NetConnection();

		connection.configuration().put(
				NetConnection.Configuration.INACTIVITY_TIMEOUT, -1);
		connection.configuration().put(
				NetConnection.Configuration.RECEIVE_BUFFER_SIZE, 256 * 1024);
		connection.configuration().put(
				NetConnection.Configuration.SEND_BUFFER_SIZE, 256 * 1024);

		this.context = context;

		try {
			connection.addEventListener(new NetConnectionListener());
			connection.connect(red5_url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private final class NetConnectionListener extends
			NetConnection.ListenerAdapter {
		/**
		 * Constructor.
		 */
		public NetConnectionListener() {
		}

		@Override
		public void onAsyncError(final INetConnection source,
				final String message, final Exception e) {
			System.out.println("NetConnection#onAsyncError: " + message + " "
					+ e);
		}

		@Override
		public void onIOError(final INetConnection source, final String message) {
			System.out.println("NetConnection#onIOError: " + message);
		}

		@Override
		public void onNetStatus(final INetConnection source,
				final Map<String, Object> info) {
			System.out.println("״̬:  NetConnection#onNetStatus: " + info);
			final Object code = info.get("code");

			if (NetConnection.CONNECT_SUCCESS.equals(code)) {
//				startVideo();
				netStream = new NetStream(connection);
			} else {

			}
		}
	}

	public void startPublish(final ICamera camera) {

//		this.netStream = new NetStream(connection);
		 netStream.attachCamera(camera, -1);
		 netStream.publish("test", NetStream.LIVE);
//		netStream.addEventListener(new NetStream.ListenerAdapter() {
//			@Override
//			public void onNetStatus(final INetStream source,
//					final Map<String, Object> info) {
//				System.out.println("Publisher#NetStream#onNetStatus: " + info);
//				final Object code = info.get("code");
//				 if (NetStream.PUBLISH_START.equals(code)) {
//					 netStream.attachCamera(camera, -1);
//				 }
//			}
//
//		});

	}
	public boolean isConnceted(){
		if(this.connection == null){
			return  false;
		}else{
			return this.connection.connected();
		}
	}
}
